<?php
/**
 *      [Haidao] (C)2013-2099 Dmibox Science and technology co., LTD.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      http://www.haidao.la
 *      tel:400-600-2042
 */
class member_address_logic extends logic
{
	public function __construct(){
		$this->table = model('member/member_address', 'table');
	}

	public function add($params = array()) {
		$params['status'] = 1;
		if(!$this->_validate($params)) {
			return false;
		}
		if($this->table->update($params) === false) {
			$this->error = $this->table->getError();
			return false;
		}
		return true;
	}

	public function edit($params = array()) {
		if($params['id'] < 1) {
			$this->error = '参数错误';
			return false;
		}
		if(!$this->_validate($params)) {
			return false;
		}
		if($this->table->update($params) === false) {
			$this->error = $this->table->getError();
			return false;
		}
		return true;
	}

	public function delete($id) {
		$isdefault = $this->table->fetch_by_id($id, 'isdefault');
		if($isdefault == 1) {
			$this->error = '不能删除默认收货地址';
			return false;
		}
		$result = $this->table->delete($id);
		if($result === FALSE) {
			$this->error = $this->table->getError();
			return false;
		}
		return TRUE;
	}

	private function _validate($params = array()) {
		if(empty($params)) {
			$this->error = '参数错误';
			return false;
		}
		if(empty($params['name'])) {
			$this->error = '收货人姓名不能为空';
			return false;
		}
		if(empty($params['mobile'])) {
			$this->error = '手机号不能为空';
			return false;
		}
		if(!is_mobile($params['mobile'])) {
			$this->error = '手机号格式不正确';
			return false;
		}
		$params['district_id'] = (int) $params['district_id'];
		if($params['district_id'] < 1) {
			$this->error = '请选择收货地区';
			return false;
		}
		/* 检测地区必须选到最下级 */
		if(model('admin/district', 'service')->get_children($params['district_id'])) {
			$this->error = '请选择下级地区';
			return false;
		}
		if(empty($params['address']) || strlen($params['address']) < 5) {
			$this->error = '详细地区必须大于5个字符';
			return false;
		}
		if(empty($params['zipcode']) && !is_zipcode($params['zipcode'])) {
			$this->error = '邮编地址为空或不合法';
			return false;
		}
		return true;
	}
}